package com.mvc.rpc.feign;

import com.mvc.common.excetion.FeignResponseException;
import com.netflix.client.ClientException;
import feign.Client;
import feign.Request;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.cloud.openfeign.ribbon.CachingSpringLoadBalancerFactory;
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;

import java.io.IOException;
import java.net.SocketTimeoutException;

/**
 * 统一fallback处理的LoadBalancer
 * @author JayEinstein
 */
@Slf4j
public class FallbackLoadBalancerFeignClient extends LoadBalancerFeignClient {

    public FallbackLoadBalancerFeignClient(Client delegate, CachingSpringLoadBalancerFactory lbClientFactory, SpringClientFactory clientFactory) {
        super(delegate, lbClientFactory, clientFactory);
    }

    @Override
    public Response execute(Request request, Request.Options options) throws IOException {
        try {
            return super.execute(request, options);
        }
        catch (SocketTimeoutException e) {
            log.info("接口请求超时", e);
            throw new FeignResponseException(FeignResponseException.Code.TIMEOUT, e);
        } catch (Exception e) {

            Throwable cause = e.getCause();

            if (cause instanceof ClientException) {
                log.info("负载均衡异常，无法找到服务", cause);
                throw new FeignResponseException(FeignResponseException.Code.CLIENT_ERROR, cause);
            }

            log.error("loadBalancer出现异常", e);
            throw new FeignResponseException(FeignResponseException.Code.UNKNOWN, e);

        }

    }
}
